Skip to content

Program operational metrics

Program-wide operational metrics.

Reads counters that live directly on the bound program object: specifically {phase}_cumulated_invocations and {phase}_cumulated_invocation_elapsed_s, which Module._maybe_reset_call_context bumps whenever the program is the entry module of a top-level call. That gives true wall-clock elapsed and invocation counts at the program boundary, not a sum of nested LM/EM per-call times.

For cost, which is paid by individual providers and tracked on each LanguageModel / EmbeddingModel, the base class also collects the LM and EM trees reachable from the program (including .fallback chains) so subclasses can sum across them.

ProgramAvgCostPerInvocation

Bases: ProgramOperationalMetric

USD per program call, inference only; use for unit cost, not totals.

Average provider cost per program invocation: the cost of the program's own calls (inference), without its judge's or optimizer's.

Example:

program.compile(
    metrics=[
        synalinks.metrics.ProgramAvgCostPerInvocation(),
    ],
)
Source code in synalinks/src/metrics/program_metrics.py
@synalinks_export("synalinks.metrics.ProgramAvgCostPerInvocation")
class ProgramAvgCostPerInvocation(ProgramOperationalMetric):
    """USD per program call, inference only; use for unit cost, not totals.

    Average provider cost per program invocation: the cost of the
    program's own calls (inference), without its judge's or optimizer's.

    Example:

    ```python
    program.compile(
        metrics=[
            synalinks.metrics.ProgramAvgCostPerInvocation(),
        ],
    )
    ```
    """

    def __init__(self, name="program_avg_cost_per_invocation", description=None):
        super().__init__(name=name, description=description)

    def result(self):
        calls = self._delta_program("invocations")
        if calls <= 0:
            return 0.0
        return self._delta_model_cost() / calls

ProgramCalls

Bases: ProgramOperationalMetric

Top-level program invocations; use to normalize other counters per call.

One increment per call to program(...), regardless of how many LM or EM calls the program makes internally.

Example:

program.compile(
    metrics=[
        synalinks.metrics.ProgramCalls(),
    ],
)
Source code in synalinks/src/metrics/program_metrics.py
@synalinks_export("synalinks.metrics.ProgramCalls")
class ProgramCalls(ProgramOperationalMetric):
    """Top-level program invocations; use to normalize other counters per call.

    One increment per call to `program(...)`, regardless of how many LM
    or EM calls the program makes internally.

    Example:

    ```python
    program.compile(
        metrics=[
            synalinks.metrics.ProgramCalls(),
        ],
    )
    ```
    """

    def __init__(self, name="program_calls", description=None):
        super().__init__(name=name, description=description)

    def result(self):
        return int(self._delta_program("invocations"))

ProgramCallsPerSecond

Bases: ProgramOperationalMetric

Program calls per wall-clock second; use for serving throughput.

Example:

program.compile(
    metrics=[
        synalinks.metrics.ProgramCallsPerSecond(),
    ],
)
Source code in synalinks/src/metrics/program_metrics.py
@synalinks_export("synalinks.metrics.ProgramCallsPerSecond")
class ProgramCallsPerSecond(ProgramOperationalMetric):
    """Program calls per wall-clock second; use for serving throughput.

    Example:

    ```python
    program.compile(
        metrics=[
            synalinks.metrics.ProgramCallsPerSecond(),
        ],
    )
    ```
    """

    direction = "up"

    def __init__(self, name="program_calls_per_second", description=None):
        super().__init__(name=name, description=description)

    def result(self):
        # Wall clock, not summed per-call time: batch calls run concurrently.
        wall = read_phase_wall_clock_s(self._phase, self._phase_clock)
        wall -= self._wall_baseline
        if wall <= 0.0:
            return 0.0
        return self._delta_program("invocations") / wall

ProgramCost

Bases: ProgramOperationalMetric

USD over every bound LM/EM in all phases; use for total spend, not per call.

Total provider cost (USD, as reported by litellm) across every LM and EM reached from the program for this run, in every phase: the program's own calls, its judge's (reward) and its optimizer's. The program object itself doesn't pay providers; cost is summed from its bound models.

Example:

program.compile(
    metrics=[
        synalinks.metrics.ProgramCost(),
    ],
)
Source code in synalinks/src/metrics/program_metrics.py
@synalinks_export("synalinks.metrics.ProgramCost")
class ProgramCost(ProgramOperationalMetric):
    """USD over every bound LM/EM in all phases; use for total spend, not per call.

    Total provider cost (USD, as reported by litellm) across every LM
    and EM reached from the program for this run, in every phase: the
    program's own calls, its judge's (reward) and its optimizer's. The program
    object itself doesn't pay providers; cost is summed from its bound models.

    Example:

    ```python
    program.compile(
        metrics=[
            synalinks.metrics.ProgramCost(),
        ],
    )
    ```
    """

    def __init__(self, name="program_cost", description=None):
        super().__init__(name=name, description=description)

    def _read_model_cost(self):
        models = self._language_models + self._embedding_models
        return sum(getattr(model, "cumulated_cost", 0) for model in models)

    def result(self):
        return float(self._delta_model_cost())

ProgramElapsedTime

Bases: ProgramOperationalMetric

Summed wall-clock seconds inside program calls; use for end-to-end time.

End-to-end wall-clock seconds spent inside program(...) during this run. Sums per-invocation wall-clock; does not double-count nested LM/EM calls.

Example:

program.compile(
    metrics=[
        synalinks.metrics.ProgramElapsedTime(),
    ],
)
Source code in synalinks/src/metrics/program_metrics.py
@synalinks_export("synalinks.metrics.ProgramElapsedTime")
class ProgramElapsedTime(ProgramOperationalMetric):
    """Summed wall-clock seconds inside program calls; use for end-to-end time.

    End-to-end wall-clock seconds spent inside `program(...)` during
    this run. Sums per-invocation wall-clock; does not double-count
    nested LM/EM calls.

    Example:

    ```python
    program.compile(
        metrics=[
            synalinks.metrics.ProgramElapsedTime(),
        ],
    )
    ```
    """

    def __init__(self, name="program_elapsed_time", description=None):
        super().__init__(name=name, description=description)

    def result(self):
        return float(self._delta_program("invocation_elapsed_s"))

ProgramOperationalMetric

Bases: Metric

Program-wide counter metric base; subclass to add one, don't compile it.

Subclasses set _phase to one of "inference", "reward", or "optimizer" to read the corresponding counter set. Counters are populated based on the active op_scope (contextvar) the trainer sets for each phase.

Example:

program.compile(
    metrics=[
        synalinks.metrics.ProgramOperationalMetric(),
    ],
)
Source code in synalinks/src/metrics/program_metrics.py
@synalinks_export(
    [
        "synalinks.metrics.ProgramOperationalMetric",
        "synalinks.ProgramOperationalMetric",
    ]
)
class ProgramOperationalMetric(Metric):
    """Program-wide counter metric base; subclass to add one, don't compile it.

    Subclasses set `_phase` to one of ``"inference"``, ``"reward"``, or
    ``"optimizer"`` to read the corresponding counter set. Counters are
    populated based on the active ``op_scope`` (contextvar) the trainer
    sets for each phase.

    Example:

    ```python
    program.compile(
        metrics=[
            synalinks.metrics.ProgramOperationalMetric(),
        ],
    )
    ```
    """

    _phase = "inference"
    direction = "down"

    def __init__(self, name=None, description=None):
        super().__init__(name=name, description=description)
        self._program = None
        self._language_models = []
        self._embedding_models = []
        self._program_baselines = {suffix: 0 for suffix in _PROGRAM_SUFFIXES}
        self._model_cost_baseline = 0.0
        self._wall_baseline = 0.0
        self._phase_clock = None

    @property
    def program(self):
        return self._program

    @property
    def language_models(self):
        return list(self._language_models)

    @property
    def embedding_models(self):
        return list(self._embedding_models)

    def bind_program(self, program):
        self._program = program
        self._language_models = language_models(program)
        self._embedding_models = embedding_models(program)
        self._phase_clock = getattr(program, "_phase_clock", None)
        self._snapshot()

    def _attr(self, suffix):
        return f"{self._phase}_cumulated_{suffix}"

    def _read_program(self, suffix):
        if self._program is None:
            return 0
        return getattr(self._program, self._attr(suffix), 0)

    def _read_model_cost(self):
        attr = self._attr("cost")
        lm_cost = sum(getattr(lm, attr, 0) for lm in self._language_models)
        em_cost = sum(getattr(em, attr, 0) for em in self._embedding_models)
        return lm_cost + em_cost

    def _snapshot(self):
        for suffix in _PROGRAM_SUFFIXES:
            self._program_baselines[suffix] = self._read_program(suffix)
        self._model_cost_baseline = self._read_model_cost()
        self._wall_baseline = read_phase_wall_clock_s(self._phase, self._phase_clock)

    def _delta_program(self, suffix):
        return self._read_program(suffix) - self._program_baselines.get(suffix, 0)

    def _delta_model_cost(self):
        return self._read_model_cost() - self._model_cost_baseline

    def reset_state(self):
        self._snapshot()

    async def update_state(self, *args, **kwargs):
        return

    def result(self):
        raise NotImplementedError

    def get_config(self):
        return {"name": self.name, "description": self.description}